//
//  ListTabItem1.swift
//  SwiftUI+MVVM+Repository
//
//  Created by 高强 on 2024/9/18.
//
//新闻item

import SwiftUI

struct NewsItem: View {
    
    @StateObject private var viewModel = NewsItemViewModel()
    
    
    var body: some View {
        List(viewModel.newsItems) { item in
            VStack(alignment: .leading) {
                Text(item.title)
                    .font(.headline)
                Text(item.createTime)
                    .font(.subheadline)
                    .foregroundColor(.gray)
            }
            .padding()
            // 上拉加载，当列表显示到最后一个item时，触发加载更多数据
            .onAppear{
                if let lastitem  = viewModel.newsItems.last,item == lastitem {
                    print("上拉加载")
                    
                    viewModel.loadMoreNews()
                }
            }
        }
        .refreshable {
            print("下拉刷新")
            //下拉刷新
            viewModel.fetchNews()
        }
        .onAppear {//首次加载
            print("首次加载")
            viewModel.fetchNews()
        }
        .alert(isPresented: $viewModel.showError) {
            Alert(title: Text("错误"), message: Text(viewModel.errorMessage), dismissButton: .default(Text("确定")))
        }
    }
    
}

#if DEBUG
struct NewsItem_Previews : PreviewProvider{
    static var previews: some View{
        NewsItem()
    }
}
#endif
